<template>
  <div class="carbon-emissionData">
    <div>
      <custom-timer type="year" title="选择年份" :is-interval="false" :picker-title="'请选择年份'" :date-value="form.year" @update:dateValue="getTime" />
      <van-radio-group v-model="radio" direction="horizontal" style="justify-content: center; margin-bottom: 0.267rem" @change="radioChange">
        <van-radio name="1">行业分析</van-radio>
        <van-radio name="2">趋势分析</van-radio>
        <!--        <van-radio name="3">区域分析</van-radio>-->
      </van-radio-group>
      <div class="loading">
        <div v-if="radio === '1'" class="text-muted my-2 ">
          碳排放总量<span class="c-text-color3 font-weight-bold"><b class="font-size-xxl">{{ datas.total }}</b>{{ datas.total === '/' ? '' : '万吨二氧化碳当量' }}</span>
        </div>
        <div v-if="radio === '2'" class="text-muted my-2">
          碳排放量环比<span class="c-text-color3 font-weight-bold">{{ datas.annulus > 0 ? '增长' : 0 > datas.annulus ? '减少' : '' }}<b class="font-size-xxl">{{ datas.annulus === '/' ? '/' : Math.abs(datas.annulus) }}</b>{{ datas.annulus === '/' ? '' : '%' }}
          </span>
        </div>
        <div class="" v-html="chartDes" />
      </div>
      <div ref="chart" style="height: 250px; width: 100%" />
    </div>
    <div>
      <customTitle :is-line="true" bg-color="#3795ff" title="企业碳排放排名分析">
        <template #right>
          <div class="timer-box">
            <van-field v-model="text" label="" placeholder="请选择分析类型" input-align="left" clickable readonly @click="showType = true" />
            <i class="iconfont down">&#xe656;</i>
          </div>
        </template>
      </customTitle>
      <!-- <customSearch ref="customSearch" style="background: #F2F2F2;color: #333;" placeholder="请输入名称" title="碳排放数据列表" :total="10" :is-super-search="false" @search="handleSearch" /> -->
      <div class="common_list loadingbottom py-0">
        <div v-for="(item, index) in tableList" :key="index" class="list_item ">
          <div class="content_area">
            <div class="number_order">{{ index + 1 }}</div>
            <div class="right_content">
              <div class="content_title" style="max-width: 100%">
                {{ item.companyName }}
              </div>
              <ul class="des-list">
                <li class="des" style="flex-direction: column">
                  <div class="d-flex">
                    <div class="label">本年度：</div>

                    <div class="value">{{ item[typeMap[text]] }}
                      <span v-if="item[typeMap[text]] === '/'" />
                      <span v-else>({{ unitMap[text] }})</span>
                    </div>
                  </div>
                  <div class="d-flex mt-1">
                    <div class="label">同比：</div>
                    <div class="">
                      <span v-if="item.emissionsAnnulus > 0" class="text-danger">↑{{ item.emissionsAnnulus }}%</span>
                      <span v-else-if="item.emissionsAnnulus < 0" class="text-success">↓{{ Math.abs(item.emissionsAnnulus) }}%</span>
                      <span v-else>{{ item.emissionsAnnulus }}{{ item.emissionsAnnulus === '/' ? '' : '%' }}</span>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-if="tableList.length == 0" description="暂无数据" />
      <!-- <customLoadmore ref="customLoadmore" :page-num="form.pageNum" :pages="pages" @load="handlePages" /> -->
    </div>
    <van-popup v-model="showType" position="bottom" get-container="body">
      <van-picker title="分析类型" show-toolbar :columns="columns" @cancel="showType = false" @confirm="onConfirm" />
    </van-popup>
  </div>
</template>

<script>
import { pieChart, lineChart, lineHorizontalChart } from '@/utils/chart.js'
import commonList from '@/assets/mixin/commonList'
import { emissionsRankAnalyse, industryAnalyse, trendAnalyse, areaAnalyse } from '@/api/carbon'
export default {
  mixins: [commonList],
  data() {
    return {
      radio: '1',
      showType: false,
      pages: 0,
      form: {
        pageNum: 1,
        pageSize: 10,
        year: new Date().getFullYear() + '',
        orderField: 'emissions',
        orderType: 'desc'
      },
      options: {},
      chart: null,
      funMap: {
        1: 'pieChart',
        2: 'lineChart',
        3: 'barChart'
      },
      tableList: [],
      chartDes: '',
      text: '碳排放量',
      columns: ['碳排放量', '万元产值（收入）二氧化碳排放（可比价）'],
      typeMap: {
        碳排放量: 'emissions',
        '万元产值（收入）二氧化碳排放（可比价）': 'outputValue'
      },
      unitMap: {
        碳排放量: '万吨二氧化碳当量',
        '万元产值（收入）二氧化碳排放（可比价）': '吨二氧化碳当量/万元'
      },
      datas: []
    }
  },
  mounted() {
    this.chart = this.$refs.chart
    this.radioChange()
    this.emissionsRankAnalyse()
  },
  methods: {
    handleSearch() {},
    async getChart() {
      const param = {
        1: industryAnalyse,
        2: trendAnalyse,
        3: areaAnalyse
      }
      const { status, data } = await param[this.radio]({ year: this.form.year })
      if (status === 0 && data) {
        this.datas = data
        if (data && (data.dataList.length || data.length) > 0) {
          this[this.funMap[this.radio]](data)
          if (this.chart) {
            const myChart = this.$echarts.init(this.chart)
            myChart.clear()
            myChart.setOption(this.options)
            window.addEventListener('resize', () => {
              myChart.resize()
            })
          }
        } else {
          this.layout.chartNoData(this.chart)
        }
      } else {
        this.layout.chartNoData(this.chart)
      }
    },
    pieChart(data) {
      // this.chartDes = '碳排放总量' + ' <span class="c-text-color3">' + data.total ? data.total : '' + ' 万tCO2e</span>'
      // this.chartDes = '碳排放总量' + ' <span class="c-text-color3">' + data.total + ' 万吨二氧化碳当量</span>'
      const seriesData = []
      data.dataList.map((v) => {
        if (v.dischargeValue === 0 || v.dischargeValue === '0.00' || v.dischargeValue === '0.0000') {
          v.dischargeValue = ''
        }
        seriesData.push({
          name: v.industryType,
          value: v.dischargeValue
        })
      })

      this.options = pieChart(
        {
          legendShow: true,
          legendBottom: 0,
          legendLeft: 'center',
          tooltipShow: true,
          tooltipFormatter: '{b}：{c}万吨二氧化碳当量'
        },
        [
          {
            type: 'pie',
            radius: ['40%', '60%'],
            data: seriesData,
            label: {
              show: true,
              formatter: '{d}%'
            }
          }
        ]
      )
      this.options.legend.icon = 'circle'
    },
    lineChart(data) {
      // let annulus = ''
      // if (Number(data.annulus) > 0) {
      //   annulus = '增长 ' + data.annulus
      // } else if (Number(data.annulus) < 0) {
      //   annulus = '减少 ' + data.annulus
      // } else {
      //   annulus = '不变'
      // }
      // this.chartDes = '碳排放量环比 <span class="c-text-color3">' + (annulus || '') + ' %</span>'
      const xData = data.dataList.map((v) => {
        return v.quarter
      })
      const seriesData1 = data.dataList.map((v) => {
        return v.currentYearValue
      })
      const seriesData2 = data.dataList.map((v) => {
        return v.lastYearValue
      })
      const legendData = data.dataList.length && data.dataList[0].currentYear ? [data.dataList[0].currentYear + '年', data.dataList[0].currentYear - 1 + '年'] : []
      this.options = lineChart(
        xData,
        [
          {
            name: legendData[0],
            data: seriesData1,
            smooth: true,
            itemStyleColor: 'rgba(30,144,255)',
            lineStyleColor: 'rgba(30,144,255)',
            areaStyleColor: 'rgba(30,144,255,0.7)'
          },
          {
            name: legendData[1],
            data: seriesData2,
            smooth: true,
            itemStyleColor: 'rgba(98,218,171)',
            lineStyleColor: 'rgba(98,218,171)',
            areaStyleColor: 'rgba(98,218,171,0.7)'
          }
        ],
        {
          tooltipShow: true,
          legendShow: true,
          isWind: true,
          legendData: legendData,
          legendBottom: 0,
          legendTop: 230,
          gridBottom: 20,
          tooltipFormatter: function(arr) {
            let str = arr[0].axisValue + '<br>'
            arr.forEach((item) => {
              str += item.marker + item.seriesName + '：' + item.value + '万吨二氧化碳当量<br>'
            })
            return str
          }
        }
      )
    },
    barChart(data) {
      const xData = data.map((v) => {
        return v.province
      })
      const seriesData = data.map((v) => {
        return v.currentyearquarter
      })
      this.options = lineHorizontalChart(
        xData,
        [
          {
            name: '碳排放量',
            type: 'bar',
            data: seriesData,
            itemStyleColor: '#6395FA'
          }
        ],
        {
          yAxisLine: true,
          xAxisLine: true,
          tooltipShow: true,
          tooltipFormatter: '{b}：{c}万吨二氧化碳当量'
        }
      )
    },
    radioChange() {
      this.options = {}
      this.chartDes = ''
      this.getChart()
    },
    async emissionsRankAnalyse() {
      this.layout.showAreaLoading(['.loadingbottom '])
      const { status, data } = await emissionsRankAnalyse(this.form)
      if (status === 0 && data) {
        data.shift()
        this.tableList = data
      }
      this.layout.hideAreaLoading(['.loadingbottom '])
    },
    handlePages(val) {
      this.form.pageNum = val
      this.emissionsRankAnalyse()
    },
    getTime(val) {
      if (val === '') {
        this.form.year = new Date().getFullYear() + ''
      } else {
        this.form.year = val
      }
      this.form.pageNum = 1
      this.tableList = []
      this.emissionsRankAnalyse()
      this.radioChange()
    },
    onConfirm(val) {
      this.text = val
      this.showType = false
      this.form.orderField = this.typeMap[val]

      this.emissionsRankAnalyse()
    }
  }
}
</script>

<style lang="scss" scoped>
.des-list {
  margin-bottom: 20px;
}
.row {
  display: flex;
  height: 35px;
  line-height: 35px;
  .strength {
    flex: 2;
    text-align: center;
  }
  .head {
    color: #000;
  }
  span {
    flex: 1;
    text-align: center;
    color: #777;
  }
}

.timer-box {
  width: 100%;
  height: auto;
  display: flex;
  align-items: center;
  border-radius: 5px;
  overflow: hidden;
  border: 1px solid rgba(233, 233, 233, 1);
  span {
    flex-shrink: 0;
    padding: 0 10px;
  }
  .van-cell {
    padding: 0 16px;
    &:active {
      background-color: rgba(0, 0, 0, 0);
    }
    .van-field__control {
      height: 25px;
      font-size: 12px;
      &:disabled {
        color: #323233;
        -webkit-text-fill-color: #323233;
      }
    }
    &::after {
      display: none;
    }
  }
  .down {
    font-size: 30px;
    color: #838282;
  }
  &.isBorder {
    border: 1px solid #e9e9e9;
  }
}
</style>
<style lang="scss">
.carbon-emissionData .ml-auto {
  width: 45%;
}
.carbon-emissionData .customSearch {
  margin-top: 10px;
  background-color: #f2f2f2 !important;
  .title {
    padding-left: 10px;
  }
  .iconfont {
    padding-right: 10px;
  }
  .title,
  .iconfont {
    color: #333;
  }
  .el-input .el-input__inner {
    color: #333;
  }
  .el-input .el-input__inner::-webkit-input-placeholder {
    color: #888 !important;
    font-weight: 400;
  }

  /* Firefox 4-18 */
  .el-input .el-input__inner:-moz-placeholder {
    color: #888 !important;
    font-weight: 400;
  }

  /* Firefox 19-50 */
  .el-input .el-input__inner::-moz-placeholder {
    color: #888 !important;
    font-weight: 400;
  }

  /* - Internet Explorer 10–11
    - Internet Explorer Mobile 10-11 */
  .el-input .el-input__inner:-ms-input-placeholder {
    color: #888 !important;
    font-weight: 400 !important;
  }

  /* Edge (also supports ::-webkit-input-placeholder) */
  .el-input .el-input__inner::-ms-input-placeholder {
    color: #888 !important;
    font-weight: 400;
  }

  /* CSS Working Draft */
  .el-input .el-input__inner::placeholder {
    color: #888 !important;
    font-weight: 400;
  }
}
</style>
